package com.imooc.springcloud.annotation;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @describte:切面流程
 * @program:spring-cloud
 * @author:zhengdp
 * @create:2021-09-28 19:41:28
 **/
@Aspect
@Component
@Slf4j
public class AccessLimiterAspect {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisScript<Boolean> rateLimitLua;

    // 切面点
    @Pointcut("@annotation(com.imooc.springcloud.annotation.AccessLimiter)")
    public void cut(){
        log.info("cut");
    }

    @Before(value = "cut()")
    public void before(JoinPoint joinPoint){
        // 限流流程
        /**
         * 1. 获得方法签名，作为methodkey
         * 2、 调用 Redis
         */
        // 获取方法签名
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        AccessLimiter annotation = method.getAnnotation(AccessLimiter.class);
        if(annotation == null){
            return ;
        }
        String key = annotation.methodKey();
        Integer limit = annotation.limit();
        if(StringUtils.isEmpty(key)){
            // 如果没有手动指定key，就将方法的签名作为key
            // 这边考虑到入参
            Class[] type = method.getParameterTypes();
            key = method.getName();
            // 循环拼接
            if(type != null){
                String paramTypes = Arrays.stream(type)
                                    .map(Class::getName)
                                    .collect(Collectors.joining(","));
                log.info("param types:"+paramTypes);
                key += "#" + paramTypes;
            }
        }
        boolean acquired = stringRedisTemplate.execute(rateLimitLua,
                Lists.newArrayList(key), // Lua脚本中的key列表
                limit.toString() // Lua脚本Value列表
        );

        if(!acquired){
            log.error("your access is blocked, key = {}",key);
            throw new RuntimeException("Your access is blocked");
        }

    }


}
